<?php
namespace Romolo\Snitso\Signal;

class Worker
{
    protected $socket;
    public $onConnect = null;
    public $onReceive = null;
    public $onClose = null;

    public function __construct(string $address)
    {
        $this->socket = stream_socket_server($address);
    }

    public function start()
    {
        $this->accept();
    }

    private function accept()
    {
        while (true) {
            $client = stream_socket_accept($this->socket);

            pcntl_signal(SIGIO, function ($sig) use ($client) {
                ($this->onConnect)($this, $client);

                $data = fread($client, 65535);
                ($this->onReceive)($this, $client, $data);
            });

            posix_kill(posix_getpid(), SIGIO);

            pcntl_signal_dispatch();
        }
    }

    public function send($client, $data)
    {
        fwrite($client, $data);
    }
}